#include "QImageShower.h"
#include "QPainter"

QImageShower::QImageShower(QWidget* parent):QWidget(parent)
{
	hasImage=false;
}


QImageShower::~QImageShower(void)
{
}

/*
void QImageShower::loadImageAndShow(const QString & str)
{
	loadImage(str);
	showImage();
}

void QImageShower::loadImage(const QString & str)
{

	QImage *qi = new QImage;
	qi->load(str);

	QPainter imgQainter;
	pixmapToShow = QPixmap::fromImage( qi->scaled(iWidth,iHeight, Qt::KeepAspectRatio) );
	imgQainter.drawPixmap(0,0,iWidth,iHeight, pixmapToShow);

}

void QImageShower::showImage()
{
	this->setPixmap(pixmapToShow);
}
*/

void QImageShower::rowSelected(QString s)
{
	
	QImage currentImage(s);
	if (currentImage.isNull()) {
		QMessageBox::information(this, tr("Image Viewer"),
			tr("Cannot load %1.").arg(s));
		return;
	}
	hasImage=true;
	image=currentImage;
	getImageRect();
	update();

}
void QImageShower::getImageRect()
{
	int imagewidth=image.width();
	int imageheight=image.height();
	int widghtwidth=width();
	int widgetheight=height();

	double factorwidth=(double)widghtwidth/imagewidth;
	double factorheight=(double)widgetheight/imageheight;

	double factor=factorheight;
	if(factorheight>factorwidth)
	{
		factor=factorwidth;
	}
	int showheight=int(imageheight*factor);
	int showwidth=int(imagewidth*factor);
	int x=(widghtwidth-showwidth)/2;
	int y=(widgetheight-showheight)/2;
	imageRect=QRect(x,y,showwidth,showheight);
}
void QImageShower::paintEvent(QPaintEvent *event)
{
	if(!hasImage)
		return;
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);	
	painter.drawImage(imageRect,image);
}
void QImageShower::resizeEvent(QResizeEvent *event)
{
	if(hasImage)
	{
	getImageRect();
	update();
	}
}